package org.example.redis;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @program: rabbitmq-study
 * @description:
 * @Version V1.0.0
 * @author: dazhi
 * @create: 2021-10-25 15:44
 **/
@RequiredArgsConstructor
@Component
public class RedisLockUtil {

    private final RedisTemplate redisTemplate;

    //加锁
    public Boolean testRedisLock(String lockKey, String requestId) {
        //设置key value，返回成功/失败，
        // 同时设置过期时间，redisTemplate 会调用 EXPIRE进行过期时间的设定，同时在设置值和过期时间时，会开启事务，保存全部成功。
        Boolean result = redisTemplate.opsForValue().setIfAbsent(lockKey, requestId, 5000, TimeUnit.SECONDS);
        if (result) {
            System.out.println("加锁成功");
            return result;
        }
        System.out.println("加锁失败");
        return false;

    }


    //解锁
    public Boolean testRedisUnLock(String key, String requestId) {
        String script =
                "if redis.call('get',KEYS[1]) == ARGV[1] then" +
                        "   return redis.call('del',KEYS[1]) " +
                        "else" +
                        "   return 0 " +
                        "end";
        DefaultRedisScript<String> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(script);
        Object result = redisTemplate.execute(redisScript, Collections.singletonList(key), requestId);
        if (result.equals(1L)) {
            return true;
        } else {
            return false;
        }

    }
}
